<?php

namespace App\Http\Controllers\Api\V1\Manager\Order;

use App\Exports\UniversalExport;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Supplier;
use App\Models\UserHome;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class IntegralOrderController extends Controller
{
    /**角色列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $userId = $request->userId;
        $userName = $request->userName;
        $userPhone = $request->userPhone;
        $supplierName = $request->supplierName;
        $wuliu_num = $request->wuliu_num;
        $name = $request->name;
        $phone = $request->phone;
        $address = $request->address;
        $ordernum = $request->ordernum;
        $status = $request->status;
        $paytype = $request->paytype;
        $createStartTime = $request->createStartTime;
        $createEndTime = $request->createEndTime;
        $payStartTime = $request->payStartTime;
        $payEndTime = $request->payEndTime;
        $shouStartTime = $request->shouStartTime;
        $shouEndTime = $request->shouEndTime;
        $paycode = $request->paycode;
        $pageSize = $request->pageSize;
        $sql = Order::select('t1.id', 't1.id as orderId', 't1.ordernum', 't1.paycode', 't2.id as userId', 't2.nickname as userName', 't2.phone as userPhone', 't1.status', 't1.price',
            't1.allprice', 't1.paytype', 't1.breakLevel', 't1.oBreak', 't1.break','t1.wuliu_num',
            't1.name', 't1.phone', 't1.address', 't3.id as supplierId', 't3.suppname as supplierName', 't1.supplier_cost', 't1.createtime as createTime', 't1.paytime as payTime', 't1.shouhuotime as shouhuoTime', 't1.use_integral')
            ->from((new Order())->getTable() . ' as t1')
            ->leftJoin((new UserHome())->getTable() . ' as t2', 't1.userhome_id', '=', 't2.id')
            ->leftJoin((new Supplier())->getTable() . ' as t3', 't1.supplier_id', '=', 't3.id')
            ->where('t1.is_integral', 1);
        $ids = $request->ids;
        $idList = [];
        if (isset($ids)) {
            $ids = explode(';', $ids);
            foreach ($ids as $v) {
                $idList[] = $v;
            }
        }
        if (isset($idList[0])) {
            $sql->whereIn('t1.id', $idList);
        }
        if (isset($createStartTime)) {
            $sql->where('t1.createtime', '>=', $createStartTime);
        }
        if (isset($createEndTime)) {
            $sql->where('t1.createtime', '<=', $createEndTime);
        }
        if (isset($payStartTime)) {
            $sql->where('t1.paytime', '>=', $payStartTime);
        }
        if (isset($payEndTime)) {
            $sql->where('t1.paytime', '<=', $payEndTime);
        }
        if (isset($shouStartTime)) {
            $sql->where('t1.shouhuotime', '>=', $shouStartTime);
        }
        if (isset($shouEndTime)) {
            $sql->where('t1.shouhuotime', '<=', $shouEndTime);
        }
        if (isset($userId)) {
            $sql->where('t1.userhome_id', $userId);
        }
        if (isset($userName)) {
            $sql->where('t2.nickname', 'like', "%$userName%");
        }
        if (isset($userPhone)) {
            $sql->where('t2.phone', 'like', "%$userPhone%");
        }
        if (isset($supplierName)) {
            $sql->where('t3.suppname', 'like', "%$supplierName%");
        }
        if (isset($wuliu_num)) {
            $sql->where('t1.wuliu_num', 'like', "%$wuliu_num%");
        }
        if (isset($name)) {
            $sql->where('t1.name', 'like', "%$name%");
        }
        if (isset($phone)) {
            $sql->where('t1.phone', 'like', "%$phone%");
        }
        if (isset($address)) {
            $sql->where('t1.address', 'like', "%$address%");
        }
        if (isset($ordernum)) {
            $sql->where('t1.ordernum', 'like', "%$ordernum%");
        }
        if (isset($status)) {
            $sql->where('t1.status', $status);
        }
        if (isset($paytype)) {
            $sql->where('t1.paytype', $paytype);
        }
        if (isset($paycode)) {
            $sql->where('t1.paycode', 'like', "%$paycode%");
        }
        if (isset($request->excel)) {
            $orderList = $sql->with(['orderDetailList' => function ($query) {
                $query->select('order_id', 'id as orderDetailId', 'goods_id', 'name', 'image', 'goods_spec_name', 'num', 'is_shouhou', 'integral', 'realityFreight', 'realityPrice', 'cost_price', 'pure_cost_price');
            }])->orderByDesc('t1.createtime')
                ->get()
                ->toArray();
            $title = ['订单号', '支付单号', '用户id', '用户电话', '用户名称', '收件人名称', '收件人电话', '收件人地址', '订单状态', '商品名称', '规格属性', '商品数量', '商品单价(积分)',
                '商品总价(积分)', '运费', '实付款', '供应商名称', '含税成本单价', '含税成本总价', '不含税成本单价', '不含税成本总价', '物流单号', '物流备注内容', '支付方式', '订单创建时间', '订单支付时间', '确认收货时间', '订单备注'];
            $data = [];
            $status = [0 => '已取消', 1 => '待支付', 2 => '已支付', 3 => '已发货', 4 => '待评价', 5 => '已完成', 6 => '售后中', 9 => '已删除'];
            $payType = [1 => '微信', 2 => '支付宝', 3 => '立减券抵扣', 4 => '积分支付'];
            foreach ($orderList as $order) {
                foreach ($order['order_detail_list'] as $orderDetail) {
                    $statusType = "未知状态";
                    if (($orderDetail['is_shouhou'] == 0) || ($orderDetail['is_shouhou'] == 3)) {
                        $statusType = $status[$order['status']];
                    } else {
                        if ($orderDetail['is_shouhou'] == 1) {
                            $statusType = "售后中";
                        }
                        if ($orderDetail['is_shouhou'] == 2) {
                            $statusType = "售后已完成";
                        }
                    }
                    $detail = [];
                    $detail[] = $order['ordernum'];
                    $detail[] = $order['paycode'];
                    $detail[] = $order['userId'];
                    $detail[] = $order['userPhone'];
                    $detail[] = $order['userName'];
                    $detail[] = $order['name'];
                    $detail[] = $order['phone'];
                    $detail[] = $order['address'];
                    $detail[] = $statusType;
                    $detail[] = $orderDetail['name'];
                    $detail[] = $orderDetail['goods_spec_name'];
                    $detail[] = $orderDetail['num'];
                    $detail[] = $orderDetail['integral'];
                    $detail[] = $orderDetail['integral'] * $orderDetail['num'];
                    $detail[] = $orderDetail['realityFreight'];
                    $detail[] = $orderDetail['realityFreight'];
                    $detail[] = $order['supplierName'];
                    $detail[] = $orderDetail['cost_price'];
                    $detail[] = $orderDetail['cost_price'] * $orderDetail['num'];
                    $detail[] = $orderDetail['pure_cost_price'];
                    $detail[] = $orderDetail['pure_cost_price'] * $orderDetail['num'];
                    $detail[] = $order['wuliu_num'];
                    $detail[] = $order['break'];
                    $detail[] = "积分";
                    if (isset($order['createTime'])) {
                        $createTime = date("Y-m-d H:i:s", $order['createTime']);
                    }else{
                        $createTime = null;
                    }
                    if (isset($order['payTime'])) {
                        $payTime = date("Y-m-d H:i:s", $order['payTime']);
                    }else{
                        $payTime = null;
                    }
                    if (isset($order['shouhuoTime'])) {
                        $shouhuoTime = date("Y-m-d H:i:s", $order['shouhuoTime']);
                    }else{
                        $shouhuoTime = null;
                    }
                    $detail[] = $createTime;
                    $detail[] = $payTime;
                    $detail[] = $shouhuoTime;
                    $detail[] = $order['oBreak'];
                    $data[] = $detail;
                }
            }
            return Excel::download(new UniversalExport($data,$title), "销售订单".date("ymdHis").'.xlsx');
        }
        $orderList = $sql->with(['orderDetailList' => function ($query) {
            $query->select('order_id', 'id as orderDetailId', 'goods_id', 'name', 'image', 'goods_spec_name', 'num', 'is_shouhou','integral', 'realityFreight', 'realityPrice', 'cost_price', 'pure_cost_price');
        }])->orderByDesc('t1.createtime')
            ->paginate($pageSize)
            ->toArray();
        $data['orderList'] = $orderList['data'];
        foreach ($data['orderList'] as $key => $value) {
            if (isset($value['createTime'])) {
                $data['orderList'][$key]['createTime'] = date("Y-m-d H:i:s", $value['createTime']);
            }
            if (isset($value['payTime'])) {
                $data['orderList'][$key]['payTime'] = date("Y-m-d H:i:s", $value['payTime']);
            }
            if (isset($value['shouhuoTime'])) {
                $data['orderList'][$key]['shouhuoTime'] = date("Y-m-d H:i:s", $value['shouhuoTime']);
            }
        }
        $data['totalNum'] = $orderList['total'];
        return $this->apiResponse($data);
    }

    public function show(Request $request, $orderId)
    {
        $order = Order::select('t1.id', 't1.id as orderId', 't1.ordernum', 't1.paycode', 't2.id as userId', 't2.nickname as userName', 't2.phone as userPhone', 't1.status',
            't1.price', 't1.allprice', 't1.paytype', 't1.breakLevel', 't1.oBreak', 't1.wuliu_num',
            't1.name', 't1.phone', 't1.address', 't3.id as supplierId', 't3.suppname as supplierName', 't1.supplier_cost', 't1.createtime as createTime', 't1.paytime as payTime',
            't1.shouhuotime as shouhuoTime', 't1.fahuotime as fahuoTime', 't1.use_integral','t1.freight')
            ->from((new Order())->getTable() . ' as t1')
            ->leftJoin((new UserHome())->getTable() . ' as t2', 't1.userhome_id', '=', 't2.id')
            ->leftJoin((new Supplier())->getTable() . ' as t3', 't1.supplier_id', '=', 't3.id')
            ->where('t1.id', $orderId)
            ->first();
        if (isset($order['createTime'])) {
            $order['createTime'] = date("Y-m-d H:i:s", $order['createTime']);
        }
        if (isset($order['payTime'])) {
            $order['payTime'] = date("Y-m-d H:i:s", $order['payTime']);
        }
        if (isset($order['shouhuoTime'])) {
            $order['shouhuoTime'] = date("Y-m-d H:i:s", $order['shouhuoTime']);
        }
        $orderDetailList = OrderDetail::select('id as orderDetailId', 'goods_id', 'name', 'image', 'goods_spec_name', 'num', 'is_shouhou', 'price', 'price as totalPrice', 'realityPrice', 'cost_price',
            'cost_price as total_cost_price', 'shuilv', 'shuilv as shuilvPrice', 'integral','realityFreight')
            ->where("order_id", $orderId)
            ->orderBy('id', 'asc')
            ->get()->toArray();
        foreach ($orderDetailList as $key => $value) {
            $orderDetailList[$key]['totalPrice'] = $value['integral'] * $value['num'];
            $orderDetailList[$key]['realityPrice'] = $value['integral'] * $value['num'];
            $orderDetailList[$key]['total_cost_price'] = $value['cost_price'] * $value['num'];
            $orderDetailList[$key]['shuilvPrice'] = intval((intval($orderDetailList[$key]['totalPrice'] * 100) * $value['shuilv']) / 100) / 100;
        }
        $order['orderDetailList'] = $orderDetailList;
        return $this->apiResponse($order);
    }
}
